import { DataService } from './../services/data.service';
import { Component, OnInit } from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';

declare var $:any;
@Component({
  selector: 'app-red-packet',
  templateUrl: './red-packet.component.html',
  styleUrls: ['./red-packet.component.css']
})
export class RedPacketComponent implements OnInit {
  constructor(public fb: FormBuilder,
    public DataService:DataService) {
}
  public reseive:boolean;
  money:number;
  public user = {
    'mobile': '',
    'code': ''
  };
  public userForm: FormGroup;
  public formErrors = {
    'mobile': '',
    'formError': '',
    'code': ''
  };
  validationMessages = {
    'mobile': {
      'required': '手机号必须输入',
      'pattern': '请输入11位手机号',
    },  
    'code': {
      'required': '验证码必须输入',
      'maxlength': '请输入4位验证码',
      'minlength': '请输入4位验证码'
    },
  };


  ngOnInit() {
    this.buildForm();
    this.reseive=this.userForm.valid && Boolean(this.money);
    this.money=2;

  }
  buildForm(): void {
    this.userForm = this.fb.group({
      "mobile": [
        this.user.mobile,
        [
          Validators.required,
          Validators.pattern("^1[345678][0-9]{9}$"),
        ]
      ],
      "code": [
        this.user.code,
        [
         Validators.required,
          Validators.maxLength(4),
          Validators.minLength(4)
        ]
      ]
    });
    this.userForm.valueChanges
      .subscribe(data => this.onValueChanged(data));
    this.onValueChanged();
   
  }
  onValueChanged(data?: any) {
    if (!this.userForm) {
      return;
    }
    this.reseive=this.userForm.valid && Boolean(this.money) ;
   
    console.log(this.reseive);
    const form = this.userForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  doRegister() {
    if (this.userForm.valid) {
      this.user = this.userForm.value;
      this.DataService.bindMobile(this.user.mobile,this.user.code)
        .subscribe(
          data => {
            $.alert("领取成功！请及时前往微信红包查看~");
          },
          error => {
            this.formErrors.formError = error.message;
            console.error(error);
          }
        );
    } else {
      this.formErrors.formError = "存在不合法的输入项，请检查。";
    }
    // console.log(JSON.stringify(this.user));
  }
  getcode(){
      let tel=$('.tel').val();
      let valid= /1[345678][0-9]{9}$/;
      if(!valid.test(tel)){
       $.alert("请填写正确的手机号~");      
      }else {
        this.user = this.userForm.value;
        this.DataService.getCode(this.user.mobile)
          .subscribe(
            data => {
              $.alert("短信验证码发送成功~");
            },
            error => {
              this.formErrors.formError = error.message;
              console.error(error);
            }
          );
        $('.getCodeBtn').attr('disabled','true');
        this.interval();
      } 
    }

      interval(){
      let i=60;
      let timer=setInterval(function(){
        $('.getCodeBtn').html(`${i}s后重新获取`);
        if(i==0){
          $('.getCodeBtn').html('获取验证码');
          $('.getCodeBtn').removeAttr('disabled');
          clearInterval(timer);
        }
        i--;
      },1000)
    }

  }

